<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Toggle Follow with Collision</title>
    <style>
        #box1 {
            width: 200px;
            height: 200px;
            background-color: red;
            border-radius: 50%;
            position: absolute;
            left: 100px;
            top: 0px;
        }

        #box2 {
            width: 200px;
            height: 200px;
            background-color: blue;
            position: absolute;
            left: 0px;
            top: 0px;
        }
    </style>
</head>

<body>
    <div id="box1"></div>  <!-- 圆形 -->
    <div id="box2"></div>  <!-- 矩形 -->

    <script>
        const box1 = document.getElementById('box1');
        const box2 = document.getElementById('box2');
        const radius = box1.offsetWidth / 2;
        let following = false;

        function handleMouseMove(event) {
            const x = event.clientX - radius;
            const y = event.clientY - radius;

            box1.style.left = x + 'px';
            box1.style.top = y + 'px';

            // 计算圆心
            const circleX = event.clientX;
            const circleY = event.clientY;

            // 蓝色方块边界
            const blockRect = box2.getBoundingClientRect();

            // 计算圆心到矩形边界最近点
            const closestX = Math.max(blockRect.left, Math.min(circleX, blockRect.right));
            const closestY = Math.max(blockRect.top, Math.min(circleY, blockRect.bottom));

            const dx = circleX - closestX;
            const dy = circleY - closestY;
            const distance = Math.sqrt(dx * dx + dy * dy);

            if (distance <= radius) {
                following = false;
                document.removeEventListener('mousemove', handleMouseMove);
                console.log('红圆碰到蓝方边缘，停止');
            }
        }

        box1.addEventListener('click', () => {
            following = !following;

            if (following) {
                document.addEventListener('mousemove', handleMouseMove);
            } else {
                document.removeEventListener('mousemove', handleMouseMove);
            }
        });

        /* 
            取消事件的冒泡
                event.stopPropagation();
                HTML 的事件流包括三个阶段：

            捕获阶段（从 document 向目标元素捕获）
            目标阶段（事件在目标元素上触发）
            冒泡阶段（事件从目标元素向 document 冒泡）
            默认情况下，事件是会冒泡的。stopPropagation() 就是让事件停留在当前元素，不再向上冒泡。
        */
    </script>
</body>

</html>